package org.ceteca.explica.client.gui.common;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import org.ceteca.explica.client.ClientContext;
import org.ceteca.explica.client.gui.ExplicaGUIBuilder;
import org.ceteca.explica.client.gui.ImageUtils;
import org.ceteca.explica.core.ExplicaException;
import org.ceteca.explica.core.InterfaceErrors;
import org.ceteca.explica.core.InterfaceExplica;
import org.ceteca.explica.core.common.BaseVO;
import org.ceteca.explica.core.common.CommonManager;
import org.ceteca.explica.core.common.CurrencyOT;
import org.ceteca.explica.core.common.FlagOT;
import org.ceteca.explica.core.partners.ContactOT;
import org.ceteca.explica.core.util.Converter;
import org.ceteca.explica.core.util.OperationResult;
import org.ceteca.javaglade.InterfaceGladeGtk;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
 * @author Juan C. Díaz (juancarlosdiaz@ceteca.net) <br>
 *         Copyright (c) 2009 Fundación Centro Tecnolóxico da Carne
 * 
 * <br>
 * <br>
 *         This program is free software: you can redistribute it and/or modify
 *         it under the terms of the GNU General Public License as published by
 *         the Free Software Foundation, either version 3 of the License, or (at
 *         your option) any later version. <br/>
 *         This program is distributed in the hope that it will be useful, but
 *         WITHOUT ANY WARRANTY 
 *         <br>without even the implied warranty of
 *         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *         General Public License for more details. <br/>
 *         You should have received a copy of the GNU General Public License
 *         along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
public class CurrencyClient extends CommonClient {

	// WIDGETS
	private Text entryCurrencyCode, entryCurrencyDescription,
			entryCurrencyConversionRate, entryCurrencyIsoCode;
	private DateTime calendarCurrencyLastUpdate;
	private Combo comboCurrencyFlag;
	private Label imageCurrencyFlag;

	private ArrayList<FlagOT> lFlags = new ArrayList<FlagOT>();

	public CurrencyClient() {

		super(CurrencyOT.class,
				InterfaceExplica.EXPLICA_EDIT_CURRENCY_GLADE_PATH,
				InterfaceExplica.EDIT_CURRENCY_DIALOG_NAME);

	}



	@Override
	public void connectSubentityButtons() {

	}

	@Override
	public BaseVO getEntityData() {
		CurrencyOT entity = new CurrencyOT();
		if (this.entEditView != null) {
			this.getWidgets();
			entity.setDescription(entryCurrencyDescription.getText());
			entity.setConversionRate(Converter.getInstance().parseFloat(
					entryCurrencyConversionRate.getText()));

			// entity.setFlag((FlagOT) comboCurrencyFlag.getData());

			entity.setCodeISO(entryCurrencyIsoCode.getText());

			entity.setLastUpdate(Converter.getInstance().toDate(
					calendarCurrencyLastUpdate));
			;

			int selectedFlag = comboCurrencyFlag.getSelectionIndex();
			entity.setFlag(lFlags.get(selectedFlag));

			if (selectedEntity != null) {
				entity.setVersion(((CurrencyOT) this.selectedEntity)
						.getVersion());
				entity.setIdCurrency(((CurrencyOT) this.selectedEntity)
						.getIdCurrency());
			}
		}

		return entity;
	}

	@Override
	public void getWidgets() {

		boolean allOk = true;
		entryCurrencyCode = (Text) this.getWidget(
				InterfaceExplica.EDIT_CURRENCY_CODE_WIDGETNAME);
		entryCurrencyDescription = (Text) this.getWidget(
				InterfaceExplica.EDIT_CURRENCY_DESCRIPTION_WIDGETNAME);
		entryCurrencyConversionRate = (Text) this.getWidget(
				InterfaceExplica.EDIT_CURRENCY_CONVERSIONRATE_WIDGETNAME);

		calendarCurrencyLastUpdate = (DateTime) this.getWidget(
				InterfaceExplica.EDIT_CURRENCY_LASTUPDATE_WIDGETNAME);
		entryCurrencyIsoCode = (Text) this.getWidget(
				InterfaceExplica.EDIT_CURRENCY_ISOCODE_WIDGETNAME);
		comboCurrencyFlag = (Combo) this.getWidget(
				InterfaceExplica.EDIT_CURRENCY_FLAG_WIDGETNAME);

		imageCurrencyFlag = (Label) this.getWidget(
				InterfaceExplica.EDIT_CURRENCY_IMAGEFLAG_WIDGETNAME);

		if (entryCurrencyCode == null) {
			this.logger.error("Error getting entry Currency Code Widget");
			allOk = false;
		}
		if (entryCurrencyDescription == null) {
			this.logger
					.error("Error getting entry Currency Description Widget");
			allOk = false;
		}
		if (entryCurrencyConversionRate == null) {
			this.logger
					.error("Error getting entry Currency Conversion Rate Widget");
			allOk = false;
		}

		if (calendarCurrencyLastUpdate == null) {
			this.logger
					.error("Error getting entry Currency Last Update Calendar Widget");
			allOk = false;
		}
		if (entryCurrencyIsoCode == null) {
			this.logger.error("Error getting entry Currency ISO Code Widget");
			allOk = false;
		}
		if (comboCurrencyFlag == null) {
			this.logger.error("Error getting entry Currency Flag Combo Widget");
			allOk = false;
		}
		if (imageCurrencyFlag == null) {
			this.logger.error("Error getting entry Currency Flag Image Widget");
			allOk = false;
		}
		if (!allOk) {
			System.exit(-1);
		}
	}

	@Override
	public void setWidgetsValues(BaseVO base) {

		CurrencyOT ent = (CurrencyOT) base;
		getWidgets();
		entryCurrencyCode.setText(Converter.getInstance().toString(
				ent.getIdCurrency()));
		entryCurrencyDescription.setText(ent.getDescription());
		entryCurrencyConversionRate.setText(Converter.getInstance().toString(
				ent.getConversionRate()));
		entryCurrencyIsoCode.setText(ent.getCodeISO());

		Converter.getInstance().setDate(calendarCurrencyLastUpdate,
				ent.getLastUpdate());

		loadFlags();
		comboCurrencyFlag.removeAll();
		int selectedFlag = -1;
		for (int i = 0; i < lFlags.size(); i++) {
			FlagOT f = lFlags.get(i);
			comboCurrencyFlag.add(f.getIdFlag() + "|" + f.getName());
			if (ent.getFlag() != null)
				if (f.getIdFlag() == ent.getFlag().getIdFlag()) {
					selectedFlag = i;
					// break;
				}
		}
		if (selectedFlag > -1 && ent.getFlag() != null)
			comboCurrencyFlag.select(selectedFlag);

		showFlagImage(ent.getFlag());

	}

	@Override
	public OperationResult validateEntity() {
		OperationResult result = new OperationResult();
		boolean datosValidos = true;
		CurrencyOT entity = (CurrencyOT) getEntityData();

		if (entity.getConversionRate() < 0)
			datosValidos = false;

		if (datosValidos)
			result.addResultMessage(OperationResult.RESULT_OK, ClientContext
					.getInstance().getMsgCatalog().newResultMessage(
							InterfaceErrors.MSG_VALIDATE_OK));
		else
			result.addResultMessage(OperationResult.RESULT_ERROR, ClientContext
					.getInstance().getMsgCatalog().newResultMessage(
							InterfaceErrors.MSG_VALIDATE_ERROR));
		return result;
	}

	private void loadFlags() {
		lFlags.clear();

		OperationResult result = new OperationResult();
		List<BaseVO> flagsList = null;
		CommonManager manager;
		try {
			manager = this.getRemote();
			flagsList = manager.queryEntities(null, "", FlagOT.class);
			result.addResultMessage(OperationResult.RESULT_OK, ClientContext
					.getInstance().getMsgCatalog().newResultMessage(
							InterfaceErrors.MSG_ENTITY_RETRIVE_OK));
		} catch (ExplicaException e) {
			result
					.addResultMessage(OperationResult.RESULT_ERROR, e
							.getResMsg());
			e.printStackTrace();
		} catch (RemoteException e) {
			result.addResultMessage(OperationResult.RESULT_ERROR, ClientContext
					.getInstance().getMsgCatalog().newResultMessage(
							InterfaceErrors.ERR_RMI_METHOD_NOT_FOUND, e));
			e.printStackTrace();
		}
		if (result.getResult() != OperationResult.RESULT_OK) {
			ExplicaGUIBuilder.getInstance().showConfirmationDialog(
					this.getEditWindow().getShell(),
					result.getFormattedResult(), "", SWT.ICON_ERROR, SWT.OK);
		} else if (flagsList != null)
			for (BaseVO bandera : flagsList)
				lFlags.add((FlagOT) bandera);

	}

	public void showFlagImage(FlagOT f) {
		if (f != null) {
			String path = f.getImage().getPath();
			Image image = ImageUtils.getInstance().getScaledImage(path, 50,
					50);
			//imageCurrencyFlag.set
			//imageCurrencyFlag.setSize(120, 120);
			imageCurrencyFlag.setImage(image);
			
		}
	}

	@Override
	public void setEditionMode(boolean enabled) {
		getWidgets();
		entryCurrencyCode.setEnabled(false);
		entryCurrencyConversionRate.setEnabled(enabled);
		entryCurrencyDescription.setEnabled(enabled);
		entryCurrencyIsoCode.setEnabled(enabled);
		calendarCurrencyLastUpdate.setEnabled(enabled);
		comboCurrencyFlag.setEnabled(enabled);

	}



	@Override
	public void buildSelectionSets() {

	}

	
	public void on_comboFlag_clicked(Event e){
		showFlagImage(lFlags.get(comboCurrencyFlag.getSelectionIndex()));
	}
	
	@Override
	public void init_specific_components() {
		
		

		// Connect the signal to the combobox to change image flag
		
		
		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, comboCurrencyFlag,
				InterfaceExplica.EXPLICA_FLAG_SELECTION_CLICKED_HANDLER, this);
/*
		EntityOT entOT = ClientContext.getInstance().getEntity(
				InterfaceExplica.EXPLICA_ENTITY_FLAG_ID);

		SubentityOT subentOT = new SubentityOT(entOT,
				InterfaceExplica.EDIT_CURRENCY_FLAG_WIDGETNAME, this);

		comboCurrencyFlag.setData(subentOT);
*/
	}



	@Override
	public void build_extension_fields_view() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void fillEntityData() {
		if (this.selectedEntity != null && this.entEditView != null) {
			getWidgets();
			setWidgetsValues((CurrencyOT) selectedEntity);
		}
	}

}
